package com.coldworks.coldjoke.task;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.manager.TopicsManager;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.util.NetworkUtil;

public class FetchTopicsTask extends BaseThread {

	private Handler handler;
	private String topicsUrl;
	private Context context;

	public FetchTopicsTask(Context context, Handler handler, String topicsUrl) {
		this.handler = handler;
		this.handler = handler;
		this.topicsUrl = topicsUrl;
	}

	@Override
	public void run() {
		DefaultHttpClient httpclient;
		HttpGet get = new HttpGet(topicsUrl);
		Message message = null;
		httpclient = BaseNetworkManager.getInstance().createHttpClient(context);

		try {
			String sessionId = UserManager.getInstance().getSessionId();
			get.setHeader("COOKIE", "webpy_session_id=" + sessionId);
			HttpResponse response = httpclient.execute(get);
			if (isInterrupted()) {
				log.info("cancelled");
				message = handler.obtainMessage(TopicsManager.REFRESH_FAIL,
						null);
				return;
			}
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}
				if (jsonObject == null) {
					log.info("error-->json=null");
					message = handler.obtainMessage(TopicsManager.REFRESH_FAIL,
							null);
					return;
				}
				log.info("succ");
				message = handler.obtainMessage(TopicsManager.REFRESH_SUCC,
						jsonObject);
				return;
			} else {
				log.info("error net-->code:"
						+ response.getStatusLine().getStatusCode());
				message = handler.obtainMessage(TopicsManager.REFRESH_FAIL,
						null);
				return;
			}
		} catch (Exception e) {
			log.error("", e);
			message = handler.obtainMessage(TopicsManager.REFRESH_FAIL, null);
			return;
		} finally {
			handler.sendMessage(message);
		}
	}
}
